package org.paybiz.core.payplatform.yeePay.service;

import org.apache.commons.httpclient.NameValuePair;
import org.apache.log4j.Logger;
import org.paybiz.constant.ErrorConstant;
import org.paybiz.core.payplatform.yeePay.ConstantYeePay;
import org.paybiz.core.payplatform.yeePay.bean.TransferToBankDO;
import org.paybiz.core.payplatform.yeePay.util.Digest;
import org.paybiz.core.payplatform.yeePay.util.HttpClientUtil;
import org.paybiz.core.payplatform.yeePay.util.PropTool;
import org.paybiz.model.ResultDO;
import org.paybiz.util.PayCenterSignature;
import org.springframework.stereotype.Service;

/**
 * Description:转账到银行卡的实现类
 * @author  LiChunming
 * @version V1.0 
 * @createDateTime：2010-11-17 上午10:33:40 
 * @Company: MSD. 
 * @Copyright: Copyright (c) 2010
 */
@Service("transferToBank")
public class TransferToBankImpl implements TransferToBank{
	private static final Logger logger=Logger.getLogger(TransferToBankImpl.class);
	private String customerNumber;
	public TransferToBankImpl(){
		customerNumber=PropTool.getValue(ConstantYeePay.MER_ID_R);
	}
	@Override
	public ResultDO Transfer2Bank(TransferToBankDO transferToBankDO) {
		ResultDO resultDO=new ResultDO();
		String keyValue=PropTool.getValue(ConstantYeePay.KEYVALUE_R);
		//获取签名
		transferToBankDO.setP1_MerId(customerNumber);
		String transferHmac=getHmac(transferToBankDO,keyValue);
		//构建参数数组
		NameValuePair[] params=new NameValuePair[]{
				new NameValuePair("p0_Cmd",transferToBankDO.getP0_Cmd()),
				new NameValuePair("p1_MerId",transferToBankDO.getP1_MerId()),
				new NameValuePair("p2_Order",transferToBankDO.getP2_Order()),
				new NameValuePair("p3_Bank",transferToBankDO.getP3_Bank()),
				new NameValuePair("p4_Amount",transferToBankDO.getP4_Amount()),
				new NameValuePair("p5_AccountName",transferToBankDO.getP5_AccountName()),
				new NameValuePair("p6_AccountNumber",transferToBankDO.getP6_AccountNumber()),
				new NameValuePair("p7_BankName",transferToBankDO.getP7_BankName()),
				new NameValuePair("p8_Province",transferToBankDO.getP8_Province()),
				new NameValuePair("p9_City",transferToBankDO.getP9_City()),
				new NameValuePair("pa_FeeType",transferToBankDO.getPa_FeeType()),
				new NameValuePair("pb_Email",transferToBankDO.getPb_Email()),
				new NameValuePair("pc_Mobile",transferToBankDO.getPc_Mobile()),
				new NameValuePair("pd_LeaveWord",transferToBankDO.getPd_LeaveWord()),
				new NameValuePair("pe_Temp",transferToBankDO.getPe_Temp()),
				new NameValuePair("pf_Url",transferToBankDO.getPf_Url()),
				new NameValuePair("pg_BankCardType",transferToBankDO.getPg_BankCardType()),
				new NameValuePair("ph_Creator",transferToBankDO.getPh_Creator()),
				new NameValuePair("pi_Auditor",transferToBankDO.getPi_Auditor()),
				new NameValuePair("pj_Urgency",transferToBankDO.getPj_Urgency()),
				new NameValuePair("hmac",transferHmac)
		};
		String url=PropTool.getValue(ConstantYeePay.TRANSFERTOBANK_URL_R);
		logger.info("\nurl:"+url);
		//发送扣费请求，同时得到返回的xml字符串
		long times=System.currentTimeMillis();
		String xmlString=HttpClientUtil.getResponseByPost(url,params);
		logger.info("\n获取易宝支付的时间为(毫秒)："+(System.currentTimeMillis()-times));
		logger.info("\n收到的结果xml字符串：\n"+xmlString);
        String cmd="";
        String orderId="";
        String result="";
        String sgin="";
        String temp="";
        //获取结果的数组
        if(null==xmlString || "".equals(xmlString.trim())){
        	 logger.info("怎么搞的易宝打款返回为空！订单号："+orderId);
        	//否则返回失败
			resultDO.setResult(1);
			resultDO.setErrId(ErrorConstant.SIGN_FAIL_ID);
			resultDO.setErrMsg(ErrorConstant.SIGN_FAIL_VALUE+"易宝打款返回xmlString为空！");
			
			return resultDO;
        }
        String [] str=xmlString.split("\n");
        temp=str[0].toString().substring(0, str[0].toString().indexOf("="));
        logger.info("temp："+temp);
        if(temp.equals("r0_Cmd")){
        	cmd=str[0].toString().replace("r0_Cmd=", "");
        	result=str[1].toString().replace("r1_Code=", "");
        	orderId=str[2].toString().replace("r2_Order=", "");
        	sgin=str[3].toString().replace("hmac=", "");
        	logger.info("结果："+result);
        	//获取结果是否为1
        	if(result.equals("1")){
        		resultDO.setResult(0);
        		 //判断签名
        		String hmac=PayCenterSignature.hmacSign(cmd+result+orderId, keyValue);
        		if(!sgin.equals(hmac)){
        			//否则返回失败
    				resultDO.setResult(1);
    				resultDO.setErrId(ErrorConstant.SIGN_FAIL_ID);
    				resultDO.setErrMsg(ErrorConstant.SIGN_FAIL_VALUE);
    				logger.info("订单号："+orderId+"第三支付返回的签名与本地签名不一致！返回签名："+sgin+"算签名："+hmac);
        		}else{
        			logger.info("打款成功！订单号："+orderId);
        		}
        	}else {
        		if(result.equals("300")){
        			logger.info("打款失败！订单号："+orderId+",原因：订单号重复！");
        			resultDO.setErrMsg("订单号重复");
        		}else if (result.equals("18")){
        			logger.info("打款失败！订单号："+orderId+",原因：公司账户余额不足！");
        			resultDO.setErrMsg("公司账户余额不足！");
        		}else if (result.equals("1000")){
        			logger.info("打款失败！订单号："+orderId+",原因：商户不存在！");
        			resultDO.setErrMsg("商户不存在！");
        		}else if (result.equals("5")){
        			logger.info("打款失败！订单号："+orderId+",原因：超过单笔限额！");
        			resultDO.setErrMsg("超过单笔限额！");
        		}else if (result.equals("-1")){
        			logger.info("打款失败！订单号："+orderId+",原因：系统异常！");
        			resultDO.setErrMsg("系统异常!");
        		}else if (result.equals("50000")){
        			logger.info("打款失败！订单号："+orderId+",原因：提交参数错误！");
        			resultDO.setErrMsg("提交参数错误!");
        		}
        		resultDO.setResult(1);
    			resultDO.setErrId("1001");
        	}
        	
        }else if(temp.equals("r0_Code")){
        	result=str[0].toString().replace("r1_Code=", "");
        	resultDO.setResult(1);
        	if(result.equals("300")){
    			logger.info("打款失败！订单号："+orderId+",原因：订单号重复！");
    			resultDO.setErrMsg("订单号重复");
    		}else if (result.equals("18")){
    			logger.info("打款失败！订单号："+orderId+",原因：公司账户余额不足！");
    			resultDO.setErrMsg("公司账户余额不足！");
    		}else if (result.equals("1000")){
    			logger.info("打款失败！订单号："+orderId+",原因：商户不存在！");
    			resultDO.setErrMsg("商户不存在！");
    		}else if (result.equals("5")){
    			logger.info("打款失败！订单号："+orderId+",原因：超过单笔限额！");
    			resultDO.setErrMsg("超过单笔限额！");
    		}else if (result.equals("-1")){
    			logger.info("打款失败！订单号："+orderId+",原因：系统异常！");
    			resultDO.setErrMsg("系统异常!");
    		}else if (result.equals("50000")){
    			logger.info("打款失败！订单号："+orderId+",原因：提交参数错误！");
    			resultDO.setErrMsg("提交参数错误!");
    		}
        	resultDO.setErrId("1001");
        }
		return resultDO;
	}
	//计算hMac
	public String getHmac(TransferToBankDO transferToBankDO,String keyValue){
		StringBuilder sValue=new StringBuilder();
		   sValue.append(transferToBankDO.getP0_Cmd()).append(transferToBankDO.getP1_MerId()).append(transferToBankDO.getP2_Order())
		 .append(transferToBankDO.getP3_Bank()).append(transferToBankDO.getP4_Amount()).append(transferToBankDO.getP5_AccountName())
		 .append(transferToBankDO.getP6_AccountNumber()).append(transferToBankDO.getP7_BankName()).append(transferToBankDO.getP8_Province())
		 .append(transferToBankDO.getP9_City()).append(transferToBankDO.getPa_FeeType()).append(transferToBankDO.getPb_Email())
		 .append(transferToBankDO.getPc_Mobile()).append(transferToBankDO.getPd_LeaveWord()).append(transferToBankDO.getPe_Temp())
		 .append(transferToBankDO.getPf_Url()).append(transferToBankDO.getPg_BankCardType()).append(transferToBankDO.getPh_Creator())
		 .append(transferToBankDO.getPi_Auditor())
		 .append(transferToBankDO.getPj_Urgency());
		return Digest.hmacSign(sValue.toString(),keyValue);
	}
}
